﻿using System;

namespace Integrity
{
  public struct OneToOneProp<TOwner, TValue>
    where TOwner : class
    where TValue : class
  {
    public Func<OneToOneProp<TValue, TOwner>> CorrProp { get; private set; }

    public OneToOneProp(Func<OneToOneProp<TValue, TOwner>> corrProp)
      : this()
    {
      CorrProp = corrProp;
    }

    public TValue SetValue(TOwner owner, TValue value)
    {
      if (ReferenceEquals(_value, value)) return;
      var oldValue = _value;
      _value = value;

      if (oldValue != null)
      {
        var corrProp = Key.CorrProp(oldValue);

        var referenceProp = corrProp as IReferenceProperty;
        if (referenceProp != null)
          referenceProp.Value = null;

      }

      if (value != null)
      {
        var corrProp = Key.CorrProp(value);
        Debug.Assert(ReferenceEquals(corrProp.Owner, value));

        var referenceProp = corrProp as IReferenceProperty;
        if (referenceProp != null)
          referenceProp.Value = Owner;
      }

      Owner.OnPropertyChanged(Key.PropertyName);
    }
  }
}
